<template>
  <div class="axiom-mobile-list">
    <!-- 头部插槽 - 允许外部自定义搜索筛选 -->
    <div v-if="$slots.header" class="list-header">
      <slot name="header" />
    </div>

    <!-- 统计信息 -->
    <div v-if="showStats" class="list-stats">
      <slot name="stats" :stats="computedStats">
        <AxiomCard>
          <div class="stats-grid">
            <!-- 默认统计：已加载 / 总数 -->
            <div v-if="!customStats" class="stat-item">
              <AxiomText type="secondary">已加载</AxiomText>
              <AxiomText weight="bold">
                {{ computedStats.loaded }} / {{
                  computedStats.total !== null && computedStats.total !== undefined
                    ? computedStats.total
                    : '∞'
                }}
              </AxiomText>
            </div>
            <div v-if="customStats" class="stat-item">
              <AxiomText type="secondary">{{ customStats.label }}</AxiomText>
              <AxiomText weight="bold">{{ customStats.value }}</AxiomText>
            </div>
          </div>
        </AxiomCard>
      </slot>
    </div>

    <!-- 列表内容 -->
    <div 
      ref="scrollContainerRef"
      class="list-container"
      :style="{ maxHeight: maxHeight }"
    >
      <div class="list-content">
        <AxiomSwipeCard
          v-for="(item, index) in items"
          :key="getItemKey(item)"
          class="list-item-card"
          :editable="enableSwipeActions"
          :deletable="enableSwipeActions"
          @click.stop="handleItemClick(item)"
          @edit="handleItemEdit(item)"
          @delete="handleItemDelete(item)"
        >
          <div class="list-item">
            <!-- 使用插槽自定义内容 -->
            <slot name="item" :item="item" :index="index">
              <!-- 默认渲染逻辑 -->
              <div class="item-content">
                <!-- 标题行 -->
                <div v-if="itemConfig.title" class="item-header">
                  <AxiomTitle 
                    :title="getFieldValue(item, itemConfig.title.field)" 
                    :level="itemConfig.title.level || 4"
                  />
                  <AxiomTag
                    v-if="itemConfig.status"
                    :label="getFieldValue(item, itemConfig.status.field)"
                    :type="getStatusType(item, itemConfig.status)"
                  />
                </div>
                
                <!-- 描述信息 -->
                <div v-if="itemConfig.description" class="item-description">
                  <AxiomText type="secondary" size="small">
                    {{ getFieldValue(item, itemConfig.description.field) }}
                  </AxiomText>
                </div>
                
                <!-- 字段信息 -->
                <AxiomSection
                  v-if="itemConfig.fields && itemConfig.fields.length > 0"
                  class="item-fields-section"
                  spacing="small"
                >
                  <AxiomGroup 
                    direction="grid" 
                    :columns="2" 
                    gap="small"
                    responsive
                  >
                    <div 
                      v-for="field in itemConfig.fields" 
                      :key="field.key"
                      class="field-item"
                    >
                      <AxiomText 
                        size="small"
                        :data-long="isLongText(formatFieldValue(item, field))"
                      >
                        {{ field.label }}: {{ formatFieldValue(item, field) }}
                      </AxiomText>
                    </div>
                  </AxiomGroup>
                </AxiomSection>
                
                <!-- 标签信息 -->
                <AxiomSection
                  v-if="itemConfig.tags"
                  class="item-tags-section"
                  spacing="small"
                >
                  <AxiomGroup direction="horizontal" gap="small" wrap>
                    <AxiomTag
                      v-for="tag in getTagsValue(item, itemConfig.tags)"
                      :key="tag"
                      :label="tag"
                      size="small"
                    />
                  </AxiomGroup>
                </AxiomSection>
                
                <!-- 操作按钮 -->
                <AxiomSection
                  v-if="itemConfig.actions && itemConfig.actions.length > 0"
                  class="item-actions-section"
                  spacing="none"
                >
                  <AxiomGroup direction="horizontal" gap="small" justify="end">
                    <AxiomButton
                      v-for="action in itemConfig.actions"
                      :key="action.key"
                      :type="action.type || 'text'"
                      :size="action.size || 'small'"
                      @click.stop="handleAction(action, item)"
                    >
                      {{ action.label }}
                    </AxiomButton>
                  </AxiomGroup>
                </AxiomSection>
              </div>
            </slot>
          </div>
        </AxiomSwipeCard>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <AxiomLoading :text="loadingText" />
        </div>
        
        <!-- 加载完成提示 -->
        <div v-if="finished && items.length > 0" class="finished-container">
          <AxiomText type="muted" size="small">{{ finishedText }}</AxiomText>
        </div>
        
        <!-- 错误提示 -->
        <div v-if="error" class="error-container">
          <AxiomText type="danger">{{ errorText || '加载失败' }}</AxiomText>
          <AxiomButton type="text" @click="handleRetry">重试</AxiomButton>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && items.length === 0 && !error" class="empty-container">
          <slot name="empty">
            <AxiomText type="muted">{{ emptyText }}</AxiomText>
          </slot>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import AxiomCard from '../common/AxiomCard.vue';
import AxiomText from '../common/AxiomText.vue';
import AxiomSwipeCard from './AxiomSwipeCard.vue';
import AxiomTitle from '../common/AxiomTitle.vue';
import AxiomTag from '../common/AxiomTag.vue';
import AxiomSection from '../common/AxiomSection.vue';
import AxiomGroup from '../common/AxiomGroup.vue';
import AxiomButton from '../common/AxiomButton.vue';
import AxiomLoading from '../common/AxiomLoading.vue';

const props = defineProps({
  items: { type: Array, default: () => [] },
  loading: { type: Boolean, default: false },
  finished: { type: Boolean, default: false },
  error: { type: [String, Error, Boolean], default: null },
  totalCount: { type: Number, default: null },
  itemConfig: { type: Object, default: () => ({}) },
  showStats: { type: Boolean, default: false },
  maxHeight: { type: String, default: 'auto' },
  loadingText: { type: String, default: '加载中...' },
  finishedText: { type: String, default: '已加载全部数据' },
  errorText: { type: String, default: '' },
  emptyText: { type: String, default: '暂无数据' },
  keyField: { type: String, default: 'id' },
  customStats: { type: Object, default: null },
  enableInfiniteScroll: { type: Boolean, default: true },
  scrollThreshold: { type: Number, default: 100 },
  enableSwipeActions: { type: Boolean, default: false }
});

const emit = defineEmits([
  'action-click', 'item-click', 'item-edit', 
  'item-delete', 'load-more', 'retry'
]);

const scrollContainerRef = ref(null);

const computedStats = computed(() => ({
  loaded: props.items.length,
  total: props.totalCount,
  custom: props.customStats?.value
}));

const getItemKey = (item) => {
  if (props.itemConfig.id) {
    if (typeof props.itemConfig.id === 'function') {
      const key = props.itemConfig.id(item);
      if (key != null) return key;
    } else if (typeof props.itemConfig.id === 'string') {
      const key = item[props.itemConfig.id];
      if (key != null) return key;
    }
  }
  return item[props.keyField] || item.id || Math.random();
};

const getFieldValue = (item, field) => {
  return field.split('.').reduce((obj, key) => obj?.[key], item) || '';
};

const getTagsValue = (item, tagsConfig) => {
  const value = getFieldValue(item, tagsConfig.field);
  return Array.isArray(value) ? value : [];
};

const getStatusType = (item, statusConfig) => {
  const value = getFieldValue(item, statusConfig.field);
  return statusConfig.typeMap?.[value] || 'default';
};

const formatFieldValue = (item, field) => {
  if (!item || !field) return '';
  const value = getFieldValue(item, field.field);
  if (value === null || value === undefined) return '';
  switch (field.type) {
    case 'date': return value ? new Date(value).toLocaleDateString() : '';
    case 'datetime': return value ? new Date(value).toLocaleString() : '';
    case 'number': return typeof value === 'number' ? value.toLocaleString() : String(value);
    case 'currency': return typeof value === 'number' ? `¥${value.toLocaleString()}` : String(value);
    case 'percent': return typeof value === 'number' ? `${(value * 100).toFixed(2)}%` : String(value);
    case 'boolean': return value ? '是' : '否';
    default: return String(value);
  }
};

const isLongText = (text) => String(text || '').length > 15;

const handleScroll = (event) => {
  if (props.loading || props.finished) return;
  
  const { scrollTop, scrollHeight, clientHeight } = event.target;
  if (scrollHeight - scrollTop - clientHeight < props.scrollThreshold) {
    emit('load-more');
  }
};

onMounted(() => {
  if (props.enableInfiniteScroll && scrollContainerRef.value) {
    scrollContainerRef.value.addEventListener('scroll', handleScroll, { passive: true });
    // Initial check
    setTimeout(() => handleScroll({ target: scrollContainerRef.value }), 500);
  }
});

onBeforeUnmount(() => {
  if (props.enableInfiniteScroll && scrollContainerRef.value) {
    scrollContainerRef.value.removeEventListener('scroll', handleScroll);
  }
});

const handleAction = (action, item) => emit('action-click', { action, item });
const handleItemClick = (item) => emit('item-click', item);
const handleItemEdit = (item) => emit('item-edit', item);
const handleItemDelete = (item) => emit('item-delete', item);
const handleRetry = () => emit('retry');

</script>

<style lang="scss">
@use '../../styles/components/mobile/axiom-mobile-list';
</style> 